/**
 * 剑指 Offer 58 - I. 翻转单词顺序
 * https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/
 */

/**
 * @param {string} s
 * @return {string}
 */
function reverseWords(s) {
  let result = '';
  for (let i = 0; i < s.length; i += 1) {
    if (s[i] !== ' ') {
      const begin = i;
      i += 1;
      while (i < s.length && s[i] !== ' ') {
        i += 1;
      }
      result = `${s.substring(begin, i)}${result ? ' ' : ''}${result}`;
    }
  }
  return result;
}

console.log(reverseWords('the sky is blue') === 'blue is sky the');
console.log(reverseWords('  hello world!  ') === 'world! hello');
console.log(reverseWords('a good   example') === 'example good a');
